import React, { useEffect, useState } from "react";
import { NavigateFunction } from "react-router-dom";
import { App as AntdApp } from "antd";
import { StyleRegistry } from "styled-jsx";
import css from 'styled-jsx/css';

import prompt from "vendor/utils/prompt";
import ProAppWrapper from 'vendor/components/pro-appWrapper';
import { ProRouter, ProRouterProps } from "vendor/components/pro-router";
import { setRequestConf, removeToken } from "vendor/utils/T/core/request";
import { InitModalMountPoint } from "vendor/components/pro-hoc/withModal";
import { getAppRoutes, setEnv, getEnv, EnumRouter, noValidateLoginRoutes, noValidateMenuPermissions, ThemeConfigProvider, useThemeToken } from "@/constants";

import { getUserInfo } from "@/components/app/sys/pages/login/api"
import { permission, EnumAuthKey } from "@/service/permission"
import { getGlobalConfig } from "./service/api/common";

// 日期国际化
import 'dayjs/locale/zh-cn';

// 引入tailwindcss
// import "tailwindcss/tailwind.css";
import "./App.scss"

interface AppProps {
  appRouterProps?: ProRouterProps;
}

const App: React.FC<AppProps> = (props) => {
  const { globalStyle, appRouterProps, proAppWrapperProps } = useGlobalConfig(props);
  return <StyleRegistry>
    <AntdApp>
      <ProAppWrapper {...proAppWrapperProps}>
        <ProRouter {...appRouterProps} />
        <InitModalMountPoint />
      </ProAppWrapper>
      {prompt.initMountPoint()}
    </AntdApp>
    <style jsx global>{globalStyle}</style>
  </StyleRegistry>
}

export default () => {
  return <ThemeConfigProvider >
    <App />
  </ThemeConfigProvider>;
}

/**
 * 初始化全局配置
 */
const useGlobalConfig = ({ appRouterProps }: AppProps) => {
  const [loading, setLoading] = useState(false);
  const { themeToken } = useThemeToken();

  // 设置request http client的配置
  // @ts-ignore
  setRequestConf({ apiDomain: getEnv().apiDomain, apiResponseCode: getEnv().apiResponseCode, });

  useEffect(() => {
    setLoading(true);
    // 用于获取全局的系统配置
    getGlobalConfig().then(resp => {
      setEnv({ globalConfig: resp.data })
      // 用于登录后获取用户配置
      const currentPathname = trimLSRlash(window.location.pathname);
      if (!noValidateLoginRoutes.map(item => trimLSRlash(item)).includes(currentPathname)) {
        getUserInfo().then(() => setLoading(false)).catch(() => setLoading(false))
      } else {
        setLoading(false);
      }
    }).catch(() => {
      setLoading(false);
    })
    
  }, []);

  return {
    appRouterProps: Object.assign({
      rootPath: EnumRouter.rootRoute,
      redirectPath: EnumRouter.appRoot,
      mounted: (navigate: NavigateFunction) => {
        // @ts-ignore
        setRequestConf({
          redirectLogin: () => {
            // 1. 清除登录用户信息
            permission.loginUser.clear();

            // 2. 清除请求token
            removeToken()

            // 3. 跳转到登录页
            navigate(EnumRouter.login, { replace: true })

            // window.location.href = EnumRouter.login;
            // if (document.querySelector("#sk-mount-modal")) document.querySelector("#sk-mount-modal").remove()
          }
        })
      },
      appRoutes: getAppRoutes(),
      authorized: {
        // 路由权限
        permissions: validatePermission(),
        noVerifyLoginPathList: noValidateLoginRoutes,
        noLoginRedirectPath: EnumRouter.login,
        checkLogin: asyncCheckLogin,
      }
    }, appRouterProps),

    proAppWrapperProps: {
      loading,
      allowBrowser: getEnv().allowBrowser,
      lang: {
        type: "zh",
        intlMessages: {}
      }
    },

    globalStyle: getGlobalStyle(themeToken),
  }
}

// 校验权限
const validatePermission = () => {
  // TODO 暂不校验菜单权限
  return null

  if (permission.isSuperAdmin()) return null;

  // 路由列表
  const pathList = Object.keys(EnumRouter)
    // @ts-ignore
    .filter((path) => permission.can(EnumAuthKey[path]))
    // @ts-ignore
    .map((key) => EnumRouter[key])
  // .filter(path => typeof path === "string")

  return [
    ...noValidateMenuPermissions,
    ...pathList
  ];
}

// 异步检查登录
const asyncCheckLogin = () => new Promise((resolve) => {
  // const { userId } = permission.loginUser.get();
  // if(!userId) return reject();
  //
  // checkLogin(false).then(() => resolve(true)).catch(() => reject());

  resolve(true);
})

// 清除左右斜线
const trimLSRlash = (str: string) => str.replace(/\/$/, "").replace(/^\//, "");

// 全局样式
const getGlobalStyle = (themeToken: any) => {
  return css.global`
    * {
      box-sizing: border-box;
    }
    html {
      height: 100%;
      body {
        height: 100%;
        margin: 0;
        padding: 0;
        color: ${themeToken.colorText};
        background: ${themeToken.custom.bodyBgColor};
        > #wrapper {
          height: 100%;
          & > .ant-app{
            height: 100%;
            position: relative;
          }
        }
      }
    }
  `
}
